<template>
  <div v-loading="loading">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>搜索</span>
        </div>
      </template>
      <el-form inline>
        <el-form-item label="文件名">
          <el-input v-model="searchCond.name" />
        </el-form-item>
        <el-form-item label="说明">
          <el-input v-model="searchCond.note" />
        </el-form-item>
        <el-form-item label="上传时间">
          <el-date-picker type="daterange" value-format="YYYY-MM-DD" v-model="searchCond.date" range-separator="到" start-placeholder="开始时间" end-placeholder="结束时间" />
        </el-form-item>
        <el-form-item label="发布状态">
          <el-radio-group v-model="searchCond.publishStatus">
            <el-radio :value="1">全部</el-radio>
            <el-radio :value="2">已发布</el-radio>
            <el-radio :value="3">未发布</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-button style="margin-left: 20px" type="primary" @click="search">搜索</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <div style="height: 10px" />
    <el-empty v-if="pageList.length === 0" description="找不到数据" />
    <el-space wrap>
      <el-card class="img-card" v-for="item in pageList" :key="item.Pk" :body-style="{ padding: '0px', marginBottom: '1px' }">
        <el-image :src="'api/Image/Thumbnail?pk=' + item?.Pk" class="img-div" :preview-src-list="['api/Image/Preview?pk=' + item?.Pk]" />
        <div style="padding: 14px">
          <div class="img-note">{{ item.ImageName }} <el-tag type="success" size="small" v-if="item.Publish">已发布</el-tag> <el-tag type="info" size="small" v-if="!item.Publish">未发布</el-tag></div>
          <div class="img-note" style="font-size: small">所需分数：{{ item.Price }}</div>
          <div class="img-note" style="font-size: small">
            热度： <el-button text size="small" @click="showDownloader(item)">{{ item.Heat }}</el-button>
          </div>
          <div style="margin-top: 10px">
            <el-button size="small" @click="modify(item)">修改</el-button>
            <el-button v-if="!item.Publish" size="small" type="success" @click="publish(item, true)">发布</el-button>
            <el-button v-if="item.Publish" size="small" @click="publish(item, false)">撤回</el-button>
            <el-button size="small" @click="download(item.Pk!, item.ImageName!)">下载</el-button>
          </div>
        </div>
      </el-card>
    </el-space>
    <div style="padding: 10px 10px; width: 100%; text-align: center" v-if="more"><el-button @click="fetchData" style="width: 80%" size="large">加载更多</el-button></div>
    <el-dialog title="维护" v-model="showEditor" width="600px">
      <el-form style="padding: 10px 10px 10px 10px" :model="current" label-width="auto">
        <el-form-item label="说明">
          <el-input v-model="current.Note" />
        </el-form-item>
        <el-form-item label="所需积分">
          <el-input-number v-model="current.Price" :min="0" :max="1000"></el-input-number>
        </el-form-item>
        <el-form-item label="选择系列">
          <el-select style="width: 200px" filterable v-model="current.Series" placeholder="选择系列">
            <el-option default-first-option v-for="seriesItem in allSeries" :key="seriesItem.Pk" :label="seriesItem.SeriesName" :value="seriesItem.Pk" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="confirm">确定</el-button>
      </template>
    </el-dialog>
    <el-dialog v-model="showHistory"> <DownloadView :imagePk="currentImage"> </DownloadView></el-dialog>
  </div>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { list, save, getImg } from '@/api/image';
import type { ImageModel } from '@/model/imagemodel';
import { useUserStore } from '@/stores/userInfo';
import { ElMessage } from 'element-plus';
import DownloadView from '@/components/DownloadView.vue';
import { listSeries } from '@/api/series';
import type { SeriesModel } from '@/model/seriesmodel';
const allSeries = ref<SeriesModel[]>([]);

listSeries().then((r) => {
  allSeries.value = r.Data!;
});
const more = ref(false);
const showHistory = ref(false);
const currentImage = ref('');
const loading = ref(false);
const pageList = ref<ImageModel[]>([]);
const onResize = () => {
  colCount.value = Math.floor(window.innerWidth / 330);
};

const searchCond = ref({ name: '', note: '', date: [], publishStatus: 1 });
const current = ref<ImageModel>({});
const showEditor = ref(false);
const colCount = ref(1);
const pageIndex = ref(1);
const pageSize = ref(10);
const download = (pk: string, name: string) => {
  const user = useUserStore();
  const url = 'api/Image/Download?pk=' + pk + '&Authorization=' + user.token;
  const a = document.createElement('a');
  a.setAttribute('target', '_blank');
  a.setAttribute('download', name);
  a.setAttribute('href', url);
  a.click();
};
const search = () => {
  pageIndex.value = 1;
  pageList.value = [];
  fetchData();
};
const fetchData = () => {
  const user = useUserStore();
  const cond: any = { pageIndex: pageIndex.value, pageSize: pageSize.value, S_Creator: 'eq(' + user.user?.UserId + ')' };
  if (searchCond.value.publishStatus === 2) {
    cond.S_Publish = 'eq(Y)';
  }
  if (searchCond.value.publishStatus === 3) {
    cond.S_Publish = 'eq(N)';
  }
  if (searchCond.value.name) {
    cond.S_ImageName = 'lk(' + searchCond.value.name + ')';
  }
  if (searchCond.value.note) {
    cond.S_Note = 'lk(' + searchCond.value.note + ')';
  }
  if (searchCond.value.date.length >= 1) {
    cond.S_CreateDate_1 = 'ge(' + searchCond.value.date[0] + ' 00:00:00)';
  }
  if (searchCond.value.date.length === 2) {
    cond.S_CreateDate_2 = 'le(' + searchCond.value.date[1] + ' 23:59:59)';
  }
  loading.value = true;
  list(cond)
    .then((r) => {
      r.Data?.forEach((r) => {
        if (!pageList.value.find((s) => s.Pk === r.Pk)) {
          pageList.value.push(r);
        }
      });
      if (r.TotalCount! <= pageList.value.length) {
        more.value = false;
        ElMessage.info('加载完成');
      } else {
        more.value = true;
      }
      loading.value = false;
      pageIndex.value += 1;
    })
    .catch(() => {
      loading.value = false;
    });
};
const modify = (item: ImageModel) => {
  current.value = item;
  showEditor.value = true;
};
const publish = (item: ImageModel, publish: boolean) => {
  const t = JSON.parse(JSON.stringify(item)) as ImageModel;
  t.Publish = publish;
  save(t)
    .then((r) => {
      current.value = r.Data![0];
      const idx = pageList.value.findIndex((s) => s.Pk === current.value.Pk);
      pageList.value.splice(idx, 1, current.value);
      ElMessage.success('发布/撤回成功.');
    })
    .catch((e) => {
      console.log(e);
    });
};
const confirm = () => {
  loading.value = true;
  save(current.value)
    .then((r) => {
      current.value = r.Data![0];
      const idx = pageList.value.findIndex((s) => s.Pk === current.value.Pk);
      pageList.value.splice(idx, 1, current.value);
      showEditor.value = false;
      loading.value = false;
      ElMessage.success('修改成功.');
    })
    .catch(() => {
      loading.value = false;
    });
};
onMounted(() => {
  onResize();
  window.addEventListener('resize', onResize);
  fetchData();
});
const showDownloader = (item: ImageModel) => {
  currentImage.value = item.Pk!;
  showHistory.value = true;
};
</script>
<style scoped>
.img-card {
  width: 290px;
  height: 340px;
}
.img-div {
  width: 100%;
  height: 200px;
}
.img-note {
  margin: 3px;
}
</style>
